package com.zj.interceptor;
import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CreateCache;
import com.zj.common.Msg;
import com.zj.exception.RequestLimitException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Component
public class RequestLimitInterceptor implements HandlerInterceptor {
    @CreateCache(name = "requestLimit",expire = 1000,timeUnit = TimeUnit.MILLISECONDS)
    private Cache jetCache;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //查询目标是否在缓存中
        Object obj = jetCache.get(request.getRemoteAddr()+request.getRequestURI());
        if (obj != null){
            //目标1s内已经发送过该请求
            throw new RequestLimitException(Msg.REQUEST_IS_HOT);
        }else {
            //目标1s内尚发送过该请求  向缓存加入该目标并放行
            jetCache.put(request.getRemoteAddr()+request.getRequestURI(),1);
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
